<?php
namespace app\index\controller;

use think\Controller;
use \Firebase\JWT\JWT;
/**
 * 公用基础控制器
 */
class BaseController extends Controller {

	protected function _initialize() {
		parent::_initialize();
		$cut_action = request()->action();
		
		if($cut_action == 'wxpay_notifyx' ||$cut_action == 'wxpay_notify' || $cut_action == 'alipay_notify' || $cut_action == 'getgoodcate'){
			return true;
		}
		
		$redirect='http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$openid = session("openid");//'otx0ewIY-HKwa5p0gql3bDfp562A';//
		$user_info=session('user_info');
		
		$user_info = db('member') -> where("open_id", $openid) -> find();
		if(!$openid||!$user_info){
			$auth_code=input("code");
			if(!$auth_code){
				session("redirect",$redirect);
				$url ='http://www.90langou.com/prox.php?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
				Header("Location: $url");
				exit;
			}
			$openid = user_wx_id($auth_code);
			$user_info = db('member') -> where("open_id", $openid) -> find();
			if($user_info) {
				session('user_id',$user_info['user_id']);
				session('user_info', $user_info);
			} else {
				$this->add_user($openid);
			}
			session("openid",$openid);
		}else{
			$is_gz=session("is_gz");
			if(!$is_gz){
				//$this->up_user($openid);
			}
//			$user_info = db('member') -> where("open_id", $openid) -> find();
//			if($user_info) {
//				session('user_info', $user_info);
//			}
//			session("openid",$openid);
//			if(!$user_info['nick_name']){
//				//$this -> redirect('index/guanzhu');
//			}
		}
		
//		$jwt = isset($_SERVER['HTTP_TOKEN']) ? $_SERVER['HTTP_TOKEN'] : '';
//		if ($jwt) {
//			try {
//				JWT::$leeway = 60;
//				$decoded = JWT::decode($jwt, config('JWT_KEY'), array('HS256'));
//				$arr = (array)$decoded;
//				if ($arr['exp'] > time()) {
//					$member = db('member')->where('password', $arr['data']->password)->find($arr['data']->id);
//					if ($member) {
//						session('user_id',$member['user_id']);
//					}
//				}
//			} catch(\Exception $e) {
//			}
//		}
//		if (!session('user_id')) {
//			$this->redirect('index/index/login');
//		} else {
//			$this->assign('maction', request()->action());
//		}
	}

	/**
	 * 发送短信
	 * $mobile 手机号
	 * $template_no 模板编号(数据库主键)，注意不是模板ID
	 */
	protected function get_code($config, $template_id, $mobile, $message) {
		$code = rand(1000, 9999);
		$data['mobile'] = $mobile;
		$data['code'] = $code;
		$data['message'] = $message;
		$data['add_time'] = now_time();
		include_once ('././extend/smsapi/smsDemo.php');
		$msg = sendSms($config, $template_id, $mobile, 'code', $code);
		if ($msg->Message == "OK") {
			$data['result'] = '发送成功';
			db('verify_code')->insert($data);
			$this->success('发送成功');
		} else {
			$err = $msg->Message;
			$data['result'] = '发送失败 - ' . $err;
			db('verify_code')->insert($data);
			$this->error('发送失败' . $err);
		}
	}	
	
		/**
	 * 修改会员
	 */
	function up_user($openid){
		$appid=config('wxpay_appid');
		$secret=config('wxpay_appsercet');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";	
		$res=file_get_contents($url);
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		$access_token=$array1['access_token'];
		$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		if(isset($array1['nickname'])){
//			$data['nick_name']=$array1['nickname'];
//			$data['logo']=$array1['headimgurl'];
//			$data['is_atten']=1;
//			$user_id=db('member')->where("open_id", $openid)->update($data);
			//$user_info = db('member') -> where("open_id", $openid) -> find();
			//session('user_info', $user_info);
		}		
	}
	
	/**
	 * 注册会员
	 */
	function add_user($openid){
		$appid=config('wxpay_appid');
		$secret=config('wxpay_appsercet');
		$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";	
		$array1=$this->get_wx($url);
//		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
//		$array1 = get_object_vars($jsondecode1);//转换成数组
		$access_token=$array1['access_token'];
		$res=file_get_contents("https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN");
		$jsondecode1 = json_decode($res); //对JSON格式的字符串进行编码
		$array1 = get_object_vars($jsondecode1);//转换成数组
		if(isset($array1['nickname'])){
			$data['nick_name']=$array1['nickname'];
			$data['logo']=$array1['headimgurl'];
		}else{
			$this -> redirect('index/register');
		}
		$data['open_id'] = $openid;
		$data['add_time'] = now_time();
		$user_id = db('member')->insert($data);
		$user_info = db('member') -> where("open_id", $openid) -> find();
		session('user_id',$user_info['user_id']);
		session('user_info', $user_info);
		return true;
	}
	
	function getopenid(){
		$redirect='https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		$auth_code=input("code");
		if(!$auth_code){
			session("redirect",$redirect);
			//$url ='https://open.weixin.qq.com/connect/oauth2/authorize?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			$url ='https://www.90langou.com/prox.php?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			//$url ='https://s.lxtx001.com/prox.php?appid='.config('wxpay_appid').'&redirect_uri='.urlencode($redirect).'&response_type=code&scope=snsapi_userinfo&state=STATE%23wechat_redirect&connect_redirect=1#wechat_redirect';
			Header("Location: $url");
			exit;
		}
		$openid=user_wx_id($auth_code);
		session("openid",$openid);
		return $openid;
	}
	
	
	public function get_wx($url)
	{
		//初始化curl
		$ch = curl_init();
		//设置超时
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,FALSE);
		curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		//运行curl，结果以jason形式返回
		$res = curl_exec($ch);
		curl_close($ch);
		//取出openid
		$data = json_decode($res,true);
//		$openid = $data['openid'];
		return $data;
	}

}
